(function ($) {
    $.fn.extend({
        "myvalidate": function () {
            return this.each(function (){
            	var $this = $(this);
            	var allObj = $this.find("input,select,textarea");

				check();
				allObj.keyup(function(){
					var $that = $(this);
            		if(checkReuired($that)){
            			checkPhone($that);
            			checkLength($that);
            			checkEqualTo($that)
            		}	            			
            		
        		});
            	function check(){
            		allObj.each(function(){
	            		var $that = $(this);
	            		if(checkReuired($that)){
	            			checkPhone($that);
	            			checkLength($that);
	            			checkEqualTo($that);
	            		}
            		});
            	}
            	function checkReuired(t){
            		if(t.attr("data-required") == "true"){//是否必填
            			if(t.val() == ""){
            			  	addError(t,t.attr("data-msg"));
            			  	return false
            			}else{
            				delError(t);
            				return true
            			}
            		}
            	}

            	function checkPhone(t){
	            	if(t.attr("data-type") == "phone"){
	            		var v = t.val();
						var mobile =  /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
						if(!mobile.test(v)){
							addError(t,t.attr("data-type-msg"))
						}else{
							delError(t);
						}
	            	}
				}
				function checkLength(t){
					if(t.attr("data-length") && t.attr("data-length") != t.val().length){
						addError(t,t.attr("data-length-msg"));
					}
				}
				function checkEqualTo(t){
					if(t.attr("data-equalTo")!="" && t.attr("data-equalTo")!=null){
						var tar = t.attr("data-equalTo");
						if(t.val() != $(document).find(tar).val()){
							addError(t,t.attr("data-equalTo-msg"));
							t.val("").focus()
						}
					}
				}
                function addError(t,msg){
            		msg = (msg==null) ? "" : msg;
					t.addClass("onErr");
			  		t.parents(".inputarea").addClass("onErr");
			  		if(t.siblings("span.onErr").length){
						t.siblings("span.onErr").html(msg);
			  		}else{
			  			t.after("<span class='onErr'>"+msg+"</span>");
			  		}
            	}
            	function delError(t){
            		t.removeClass("onErr");
    				t.parents(".inputarea").removeClass("onErr");
    				t.siblings("span.onErr").remove();
            	}	
            });
        }
    });
})(jQuery);